package com.itheima.kafka.stream;

import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;

import java.util.Arrays;
import java.util.Properties;

public class KafkaStreamFastStart {

    public static void main(String[] args) {

        //1 kafka配置信息
        Properties prop = new Properties();
        prop.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.200.129:9092");
        prop.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
        prop.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-sample");

        //2 stream构建器
        StreamsBuilder builder = new StreamsBuilder();

        // 流式计算
        streamProcessor(builder);

        //3 创建 kafkaStreams
        KafkaStreams kafkaStreams = new KafkaStreams(builder.build(), prop);

        //4 开启kafka流计算
        System.out.println("streamProcessor start: ");
        kafkaStreams.start();
    }

    private static void streamProcessor(StreamsBuilder builder) {
        // 接收生产者发送消息
        KStream<String, String> stream = builder.stream("itcast-topic-input");
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
            @Override
            public Iterable<String> apply(String value) {
                // value 接收消息的具体内容
                System.out.println("消息内容："+value);
                return Arrays.asList(value.split(" "));
            }
        })
                // 根据value进行分组
                .groupBy((key,value)->value)
                // 聚合计算时间间隔
                .windowedBy(TimeWindows.of(5000))
                // 聚合查询：求单词总个数
                .count()
                // 转成 KStream
                .toStream()
                // 处理后结果key和value转成string
                .map((key, value) -> {
                    return new KeyValue<>(key.key().toString(), value.toString());
                })
                // 处理后的结果转发给消费方
                .to("itcast-topic-output");
    }
}